package com.baitiaojun.video.aspect;

import com.baitiaojun.api.util.JSR303Util;
import com.baitiaojun.api.vo.JsonRes;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

/**
 * @类名 JSR303Aspect
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2022/12/8 14:27
 * @版本 1.0
 */
@Order(1)
@Component
@Aspect
public class JSR303Aspect {

    @Pointcut("@annotation(com.baitiaojun.api.annotation.JSR303Verify)")
    public void pointCut() {}

    @Around("pointCut()")
    public JsonRes around(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
                BindingResult result = (BindingResult) arg;
                if (result.hasErrors()) {
                    return JsonRes.builder().error().data(JSR303Util.validate(result));
                }
            }
        }
        return (JsonRes) point.proceed();
    }
}
